package com.hanhai.zrb.backend.web.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hanhai.common.cache.Cache;
import com.hanhai.common.consts.GlobalConst;
import com.hanhai.common.util.CommonUtil;
import com.hanhai.zrb.backend.util.BackendLoginUtil;

public class BackendLoginInterceptor extends HandlerInterceptorAdapter {

	private String loginUrl;

	protected String loginCookieName = GlobalConst.BackendCookieName;
	@Resource
	protected Cache loginCache;
	public static Logger logger = Logger
			.getLogger(BackendLoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		BackendLoginUtil.setCurrentUser(null);
		// User项目也需要响应图片
		boolean b = handler instanceof HandlerMethod;
		if (!b) {
			return true;
		}
		BackendLoginUtil.initCurrentUser(request, loginCache);

		boolean exist = CommonUtil.hasLoginNeedless(handler);
		if (exist) {
			return true;
		}

		// 需要登录的
		if (BackendLoginUtil.getCurrentUser() != null) {
			return true;
		} else {
			// 需要登录，但是没有登录
			// 异步
			if (CommonUtil.isAjaxRequest(request)) {
				//CommonUtil.jsonLogin(response);
				response.setContentType("text/html;charset=utf-8");
				response.getWriter().write("<script language = \"javascript\">");
				response.getWriter().write("window.parent.location='" + request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"+ "';");
				response.getWriter().write("alert('会话过期,请先登录!!')");
				response.getWriter().write("</script>");
			}
			// 同步
			else {
				response.sendRedirect(loginUrl);
			}
			return false;
		}
		//return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginCenterUrl) {
		this.loginUrl = loginCenterUrl;
	}

}
